import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import cookie from 'js-cookie'

// 创建axios实例
const service = axios.create({
  baseURL:  'http://localhost:8101',
  timeout: 5000 // 请求超时时间
})

// http request拦截器
service.interceptors.request.use(
    config => {
    // 判断是否存在token 
    if(cookie.get('token')){
      //token放入到cookie中
      config.headers['token'] = cookie.get('token')
    } 
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

//http response 拦截器
service.interceptors.response.use(
  response => {

  //状态码为 208
  if(response.data.code === 208){
    //弹出登录输入框
    loginEvent.$emit('loginDialogEvent')
    return
    }
    else{
      /**
       *code为非200是抛错 可结合自己业务进行修改
      */
      const res = response.data
      if (res.code !== 200) {
        Message({
          message: res.message,
          type: 'error',
          duration: 5 * 1000
        })
        return Promise.reject('error')
      } else {
        return response.data
      }
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
